//
//  AXFSuperMarketController.swift
//  SpuerYangAngWang
//
//  Created by 杨茂盛 on 2016/12/22.
//  Copyright © 2016年 杨茂盛. All rights reserved.
//

import UIKit
import SnapKit
import YYModel
import SVProgressHUD
private let cellId1 = "cellId1"
private let cellId2 = "productsId"
class AXFSuperMarketController:AXFBaseController,UITableViewDataSource,UITableViewDelegate,CAAnimationDelegate {
    
    //判断是否是左边 tableview
    var isLeft = false
    
    //记录 id
    var idString:String?
    
    //MARK: 属性
    var leftDataSource:[AXFSuperModel]?
    
    //左右两个tableview
    let leftTableView = UITableView.init()
    var rightTbleView = UITableView.init()
    var rmImgLayer = [CALayer]()
    //记录当前购买商品的集合
     var shopArray = [ZHSellFastModel]() as! NSMutableArray
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //进入界面之前先让 tableview 隐藏,加载完数据之后再显示
        self.leftTableView.isHidden = true
        self.rightTbleView.isHidden = true
        SVProgressHUD.show(withStatus: "正在刷新哦,请稍等")

        //初始化可变数组
       self.shopArray = NSMutableArray()
        
        //搭建 UI
        self .setUI()
        
        //注册通知
        self.registerNofication()
    }
    
    //MARK: 注册clickFoodView发出的通知
   private func registerNofication(){
    NotificationCenter.default.addObserver(self, selector: #selector(incrementNofication(noti:)), name: NSNotification.Name(rawValue: AddBtnNotification), object: nil)

    NotificationCenter.default.addObserver(self, selector: #selector(dcrementNofication(noti:)), name: NSNotification.Name(rawValue: ReduceBtnNotification), object: nil)
    }
    
    //MARK: 减号按钮
    func dcrementNofication(noti:NSNotification){
        let rightModel = noti.object as! ZHSellFastModel
        if rightModel.count == 0 {
            // count 是记录当前的菜品被点了几份
            // 当count = 0, 就意味着, 这个菜没有被点 , 就没有必要去放到购物车中
            // 把这个模型从foodArray中移除
            self.shopArray.remove(rightModel)
        }
    }
    //加号按钮
    func incrementNofication(noti:NSNotification){
        let rightModel = noti.object as! ZHSellFastModel
        let beginPoint = noti.userInfo!["point"] as! CGPoint
   
        let redIMageView = noti.userInfo!["goodsImageView"] as!UIImageView
        let imgLayer = CALayer()
        
        imgLayer.frame = redIMageView.frame
        imgLayer.contents = redIMageView.layer.contents
        self.view.layer.addSublayer(imgLayer)
        //控制点
        let controlPotint = CGPoint.init(x: beginPoint.x, y: beginPoint.y-150)
        //终点 购物车 tabbar 的位置
           let endPoint = CGPoint(x: ScreenWidth - ScreenWidth / 4 - ScreenWidth / 8 - 4, y: self.view.layer.bounds.size.height - 40);
        //画抛物线
        //创建路径
        let path = UIBezierPath()
        //给路径添加起点
        path.move(to: beginPoint)
        //创建一个抛物线的路径
        path.addQuadCurve(to: endPoint, controlPoint: controlPotint)
        //添加关键帧动画
        let keyAnimation = CAKeyframeAnimation.init(keyPath: "position")
        //动画的时间
        keyAnimation.duration = 1
        //动画的路径等于抛物线的路径
        keyAnimation.path = path.cgPath
        //MARK: 让动画结束之后不闪烁
        keyAnimation.isRemovedOnCompletion = false
        keyAnimation.fillMode = kCAFillModeForwards

        rmImgLayer.append(imgLayer)
    
        
        //MARK: 添加动画
        let opacityAnimation = CABasicAnimation(keyPath: "opacity")
        opacityAnimation.fromValue = 1
        opacityAnimation.toValue = 0.7
        opacityAnimation.fillMode = kCAFillModeForwards
        opacityAnimation.isRemovedOnCompletion = true
        
        let transformAnimation = CABasicAnimation(keyPath: "transform")
        transformAnimation.fromValue = NSValue(caTransform3D: CATransform3DIdentity)
        transformAnimation.toValue = NSValue(caTransform3D: CATransform3DScale(CATransform3DIdentity, 0.3, 0.3, 1))
        
        let groupAnimation = CAAnimationGroup()
        groupAnimation.animations = [keyAnimation, transformAnimation, opacityAnimation];
        groupAnimation.duration = 0.8
        groupAnimation.isRemovedOnCompletion = false
        groupAnimation.fillMode = kCAFillModeForwards
                //设置代理
        groupAnimation.delegate = self;
        imgLayer.add(groupAnimation, forKey: nil)
        
        if !self.shopArray.contains(rightModel) {
            self.shopArray.add(rightModel)
        }
    }
    //MARK: 动画的代理
    func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
        //获取当前的图片
       let layer =  rmImgLayer.first
        layer?.isHidden = true
        layer?.removeFromSuperlayer()
        rmImgLayer.removeFirst()
    }
    
    
    //MARK: 搭建 UI 界面
    func setUI(){        
        self.view.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
        //添加 tableview 左边、右边
        self.view.addSubview(self.leftTableView)
        self.view.addSubview(rightTbleView)
        self.leftTableView.snp.makeConstraints { (make) in
            make.leading.bottom.top.equalTo(self.view)
            make.width.equalTo(90)
        }
        self.rightTbleView.snp.makeConstraints { (make) in
            make.leading.equalTo(self.leftTableView.snp.trailing)
            make.trailing.bottom.top.equalTo(self.view)
        }
        
        self.leftTableView.register(UITableViewCell.self , forCellReuseIdentifier: cellId1)
        let productNib = UINib.init(nibName: "AXFProductsCell", bundle: nil)
        self.rightTbleView.register(productNib, forCellReuseIdentifier: cellId2)
//        self.rightTbleView.register(UITableViewCell.self , forCellReuseIdentifier: cellId2)
        //调整右边 tableview
        self.rightTbleView.contentInset = UIEdgeInsetsMake(64, 0, 0, 0)
        self.leftTableView.dataSource = self
        self.rightTbleView.dataSource = self
        
        self.rightTbleView.delegate = self
        self.leftTableView.delegate = self
        
        self.rightTbleView.rowHeight = 120
        
        self.rightTbleView.contentInset.bottom = 40
    }
    
    //----------------------dataSource----------------------------------
    func numberOfSections(in tableView: UITableView) -> Int {
        if tableView == leftTableView {
            return 1
        }else{
        return self.leftDataSource?.count ?? 0
        }
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if tableView == self.leftTableView {
            return self.leftDataSource?.count ?? 0
        }else{

        return self.leftDataSource?[section].products.count ?? 0
        }
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
           var cell = UITableViewCell()
        //左边 cell
        if tableView == self.leftTableView {
            cell = tableView.dequeueReusableCell(withIdentifier: cellId1, for: indexPath)
            cell.separatorInset = UIEdgeInsets.init(top: 0, left: 0, bottom: 0, right: 0)

            let model = self.leftDataSource![indexPath.row]
            cell.backgroundColor = #colorLiteral(red: 0.882621612, green: 0.882621612, blue: 0.882621612, alpha: 1)
            cell.textLabel?.font = UIFont.systemFont(ofSize: 14)
            cell.textLabel?.text = model.name
            let view = UIView.init()
            let line = UIView.init() //cell 的左边线条
            line.backgroundColor = #colorLiteral(red: 0.9529411793, green: 0.6862745285, blue: 0.1333333403, alpha: 1)
            view.addSubview(line)
            
            line.snp.makeConstraints { (make) in
                make.centerY.equalTo(view);
                make.width.equalTo(2);
                make.height.equalTo(25);
                make.leading.equalTo(6);
            }
            view.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
            cell.selectedBackgroundView = view
            return cell
        }
        //右边 cell
      let productCell = tableView.dequeueReusableCell(withIdentifier: cellId2, for: indexPath) as! AXFProductsCell
        cell.separatorInset = UIEdgeInsets.init(top: 0, left: 0, bottom: 0, right: 0)
        let model = self.leftDataSource![indexPath.section].products[indexPath.row]
        productCell.model = model
        return productCell
    }
    
    //MARK: 返回右边 tableview 的组头文字
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        if tableView == self.leftTableView {
            return ""
        }
        let headText = UILabel.init()
        headText.text = self.leftDataSource?[section].name ?? ""
        headText.font = UIFont.systemFont(ofSize: 7)
        return headText.text

    }
    //返回 组头 view
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if tableView == self.leftTableView{
            return nil
        }else{
            let headText = UILabel.init()
            headText.text = self.leftDataSource?[section].name ?? ""
            headText.font = UIFont.systemFont(ofSize: 14)
            headText.textColor = #colorLiteral(red: 0.501960814, green: 0.501960814, blue: 0.501960814, alpha: 1)
            headText.backgroundColor = #colorLiteral(red: 0.882621612, green: 0.882621612, blue: 0.882621612, alpha: 1)
            headText.alpha = 0.9
            return headText
        }
    }
    //MARK: 返回组头高度
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if tableView == self.leftTableView {
            return 0.0
        }
        return 30
    }
    //MARK: cell的点击方法(解决左边点击右边滚动)
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if tableView == self.leftTableView {
            self.isLeft = true
            let leftIndexpath = NSIndexPath.init(row: 0, section: indexPath.row)
            //计算scrollview滚动的位置

            //让右边的tableview滚到相应的位置
            self.rightTbleView.scrollToRow(at: leftIndexpath as IndexPath, at: .top, animated: true)
        }
        if tableView == self.rightTbleView {
            //点击右边 cell 进行跳转
            let vc = AXFSuperMarketDetailController()
            let model = self.leftDataSource![indexPath.section].products[indexPath.row]
            vc.myTitle = model.name
            vc.dataSource = model
            self.navigationController?.pushViewController(vc, animated: true)
        }
    }
    //MARK: 实现右边tableview滚动让左边也跟着滚动
    func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        if tableView == self.rightTbleView {
            if self.isLeft {
                return
            }
            //获取右边 tableview 的 indexpath
            let arrayPath:[Any] = tableView.indexPathsForVisibleRows!
            let path = arrayPath.first as! NSIndexPath
            let newPath:NSIndexPath = NSIndexPath.init(row: path.section, section: 0)
            self.leftTableView.selectRow(at: newPath as IndexPath, animated: true, scrollPosition: .top)
        }
    }
    //MARK: //如果是右边的tableview,那么久禁止左边
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        if scrollView == self.rightTbleView {
            self.isLeft = false
        }
    }
    
    
    //MARK: 一进入界面就开始刷新数据
    override func viewWillAppear(_ animated: Bool) {
        //加载数据
        AXFSuperModel.shared.loadData { (isSucess, dataSource) in
            //赋值
            if isSucess{
                self.leftDataSource = dataSource
                OperationQueue.main.addOperation {
                    SVProgressHUD.dismiss()
                    //加载完成后显示
                    self.leftTableView.isHidden = false
                    self.rightTbleView.isHidden = false
                    self.leftTableView.reloadData()
                    self.rightTbleView.reloadData()
                }
            }
        }

    }
    //视图即将消失的时候移除刷新
    override func viewWillDisappear(_ animated: Bool) {
        SVProgressHUD.dismiss()
    }
}
